//
//  MQUserinfoviewViewController.m
//  meiquan
//
//  Created by hejingjin on 2017/11/4.
//  Copyright © 2017年 mq. All rights reserved.
//

#import "MQUserinfoviewViewController.h"

#import "MQLoginAndRegiterViewController.h"
#import "MQMineCell.h"
#import "MQNavigationViewController.h"
#import "MQBaseUserInfoModel.h"
#import "ZHPickView.h"
#import "MQRequestTools.h"
#import "MQAddressView.h"
#import "MBProgressHUD+MJ.h"

@interface MQUserinfoviewViewController ()<UITableViewDelegate,UITableViewDataSource, ZHPickViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource>
{
    NSInteger _provinceIndex;   // 省份选择 记录
    NSInteger _cityIndex;       // 市选择 记录
    NSInteger _districtIndex;   // 区选择 记录

}

@property(nonatomic,strong)UITableView *userinfotableview;

@property(nonatomic,strong)NSArray *titlearray;
@property (nonatomic, strong) NSMutableArray<NSString *> *detailAry;

@property (nonatomic, strong) ZHPickView *genderPicker;

@property (nonatomic, strong) ZHPickView *agePicker;

@property (nonatomic, strong) ZHPickView *areaPicker;
@property(nonatomic,strong)MQAddressView *adderssview;

@property (nonatomic, strong) NSArray *areaAry;
@end

@implementation MQUserinfoviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    MQBaseUserInfoModel *model = [MQBaseUserInfoModel shareInstant];
    [model loadUserinfoFromSadeBox];
    _titlearray = @[@"昵称",@"性别",@"生日",@"地区"];
    _detailAry = [NSMutableArray arrayWithArray:@[model.username, model.gender?model.gender:@"", model.birthday?model.birthday:@"", model.area?model.area:@""]];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    NSString *dataFilePath = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:dataFilePath];
    self.areaAry = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    [self setupMainInterface];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:(CGRectMake(0, 0, 40, 40))];
    [btn setTitle:@"保存" forState:(UIControlStateNormal)];
    [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(savePress) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)setupMainInterface{
    
    self.view.backgroundColor = BSTColorFromRGB(0xefefef);
    
    
    
    [self.view addSubview:self.userinfotableview];
    
    UIButton *logoutbutton = [[UIButton alloc] init];
    
    logoutbutton.bst_x = 0;
    logoutbutton.bst_height = 49;
    logoutbutton.bst_width = BSTScreenW;
    logoutbutton.bst_y = BSTScreenH - 49;
    logoutbutton.backgroundColor = BSTColorFromRGB(0xff8e01);
    [logoutbutton setTitle:@"退出登录" forState:UIControlStateNormal];
    [logoutbutton addTarget:self action:@selector(buttonpressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:logoutbutton];
    
    _adderssview = [MQAddressView loadaddressviews];
    _adderssview.bst_x = 0;
    _adderssview.bst_height = BSTScreenH * 0.3;
    _adderssview.bst_y = BSTScreenH * 0.7;
    _adderssview.bst_width = BSTScreenW;
    _adderssview.pickerviews.delegate = self;
    _adderssview.pickerviews.dataSource = self;
    _adderssview.hidden = YES;
    [_adderssview.cancelbutton addTarget:self action:@selector(cancelbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_adderssview.makesurebutton addTarget:self action:@selector(makesurebuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_adderssview];
}

-(void)buttonpressed{
    AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    MQLoginAndRegiterViewController *loginandregistervc = [[MQLoginAndRegiterViewController alloc] init];
    
    MQNavigationViewController *loginnavvc = [[MQNavigationViewController alloc] initWithRootViewController:loginandregistervc];
    appDelegate.window.rootViewController = loginnavvc;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MQMineCell *cell = [MQMineCell cellWIthTableview:tableView];
    cell.namelabel.text = _titlearray[indexPath.row];
    cell.valuelabel.text = _detailAry[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return;
    }
    
    ZHPickView *picker;
    
    if (indexPath.row == 1) {
        picker = [[ZHPickView alloc] initPickviewWithArray:@[@"男", @"女"] isHaveNavControler:NO];
        self.genderPicker = picker;
    }
    if (indexPath.row == 2) {
        picker = [[ZHPickView alloc] initDatePickWithDate:[NSDate date] datePickerMode:(UIDatePickerModeDate) isHaveNavControler:NO];
        self.agePicker = picker;
    }
    picker.delegate = self;
    [self.view addSubview:picker];
    
    if (indexPath.row == 3) {
        self.adderssview.hidden = NO;
    }
}

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString
{
    if (pickView == self.genderPicker) {
        [self.detailAry replaceObjectAtIndex:1 withObject:resultString];
    }
    if (pickView == self.agePicker) {
        [self.detailAry replaceObjectAtIndex:2 withObject:resultString];
    }
    [self.userinfotableview reloadData];
    NSLog(@"--%@", resultString);
}

-(void)cancelbuttonPressed:(UIButton *)semnder{
    //     [self.view bringSubviewToFront:_adderssview];
    [self.view sendSubviewToBack:_adderssview];
    _provinceIndex = _cityIndex = _districtIndex = 0;
    _adderssview.hidden = YES;
    [_adderssview.pickerviews reloadAllComponents];
}

-(void)makesurebuttonPressed:(UIButton *)sender{
    NSString *address = [NSString stringWithFormat:@"%@ %@ %@", self.areaAry[_provinceIndex][@"name"], self.areaAry[_provinceIndex][@"list"][_cityIndex][@"name"], self.areaAry[_provinceIndex][@"list"][_cityIndex][@"list"][_districtIndex][@"name"]];
    //    NSLog(@"%@",address);
    _adderssview.hidden = YES;
    [self.detailAry replaceObjectAtIndex:3 withObject:address];
    [self.userinfotableview reloadData];
    [self.view sendSubviewToBack:_adderssview];
}


#pragma mark - UIPicker Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if(component == 0){
        return self.areaAry.count;
    }
    else if (component == 1){
        return [self.areaAry[_provinceIndex][@"list"] count];
    }
    else{
        return [self.areaAry[_provinceIndex][@"list"][_cityIndex][@"list"] count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if(component == 0){
        return self.areaAry[row][@"name"];
    }
    else if (component == 1){
        return self.areaAry[_provinceIndex][@"list"][row][@"name"];
    }
    else{
        return self.areaAry[_provinceIndex][@"list"][_cityIndex][@"list"][row][@"name"];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return BSTScreenW/3;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if(component == 0){
        _provinceIndex = row;
        _cityIndex = 0;
        _districtIndex = 0;
        [self.adderssview.pickerviews reloadComponent:1];
        [self.adderssview.pickerviews reloadComponent:2];
    }
    else if (component == 1){
        _cityIndex = row;
        _districtIndex = 0;
        [self.adderssview.pickerviews reloadComponent:2];
    }
    else{
        _districtIndex = row;
    }
    // 重置当前选中项
    [self resetPickerSelectRow];
}
-(void)resetPickerSelectRow
{
    [self.adderssview.pickerviews selectRow:_provinceIndex inComponent:0 animated:YES];
    [self.adderssview.pickerviews selectRow:_cityIndex inComponent:1 animated:YES];
    [self.adderssview.pickerviews selectRow:_districtIndex inComponent:2 animated:YES];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        pickerLabel.minimumScaleFactor = 8.;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}


-(void)savePress{
    
    MQBaseUserInfoModel *model = [MQBaseUserInfoModel shareInstant];
    [model loadUserinfoFromSadeBox];
    
    NSArray *areaAry = [_detailAry[3] componentsSeparatedByString:@" "];

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"realName"] = _detailAry[0];
    dic[@"birth"] = _detailAry[2];
    dic[@"sex"] = [_detailAry[1] isEqualToString:@"男"]? @"1" : @"0";
    dic[@"provinceName"] = areaAry[0];
    dic[@"cityName"] = areaAry[1];
    dic[@"areaName"] = areaAry[2];
    dic[@"userId"] = model.userId;
    dic[@"id"] = [NSString stringWithFormat:@"%@", model.userNormalId];
    dic[@"addr"] = @"";
    [MBProgressHUD showMessage:@"正在保存，请稍后..."];
    [MQRequestTools POSTWithMethod:userNormal_update params:dic success:^(id json) {
        [MBProgressHUD hideHUD];
        [iToastUtil displayMsg:@"保存成功"];
        model.gender = self.detailAry[1];
        model.birthday = self.detailAry[2];
        model.area = self.detailAry[3];
        [model saveUserInfoToSadeBox];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        [iToastUtil displayMsg:@"保存失败"];

    }];
}

-(UITableView *)userinfotableview{
    
    
    if (!_userinfotableview) {
        
        _userinfotableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, BSTScreenW, 44 * 4 + NAVHEIGHT) style:UITableViewStylePlain];
        _userinfotableview.delegate = self;
        _userinfotableview.dataSource = self;
        _userinfotableview.backgroundColor = BSTColorFromRGB(0xf5f5f5);
        _userinfotableview.showsVerticalScrollIndicator = NO;
        _userinfotableview.bounces = NO;
        UIView *footerview = [UIView new];
        _userinfotableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        footerview.backgroundColor = BSTColorFromRGB(0xf5f5f5);
        _userinfotableview.tableFooterView = footerview;
        
    }
    return _userinfotableview;
    
    
}


@end
